Source Code Viewer - Example 2 - AbstractInMemoryTable

package name.matthewgreet.example2.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Describes an readonly, in-memory table.  This exists as part of a demonstration in place of actual database tables.
 *
 * @param <K> Type of primary key, typically Integer.
 * @param <T> Class of Data Transfer Object describing a record.
 */
public abstract class AbstractInMemoryTable<K extends Comparable<K>,T extends AbstractRecord<K>> {
	private Map<K,T> table;
	
	public AbstractInMemoryTable() {
		super();
		
		table = new HashMap<>();
		Collection<T> initialData = initialData();
		for (T record: initialData) {
			table.put(record.getPrimaryKey(), record);
		}
		initIndices(initialData);
	}
	
	protected Map<K,T> getTable() {
		return table;
	}
	
	protected abstract Collection<T> initialData();
	
	protected abstract void initIndices(Collection<T> initialData);
	
	public Collection<T> findAll() {
		return table.values();
	}

	/**
	 * Returns record by primary key, of null if not found. 
	 */
	public T findByPrimaryKey(K key) {
		return table.get(key);
	}
	
	public Collection<T> findByPrimaryKeys(Collection<K> keys) {
		T record;
		Collection<T> result;
		
		result = new ArrayList<>();
		for (K key: keys) {
			record = table.get(key);
			if (record != null) {
				result.add(record);
			}
		}
		return result;
	}

}